package server

import (
	"easy-note/config"
	"easy-note/gateway/handler"
	"easy-note/gateway/routers"
	"easy-note/note/kitex_gen/note/note"
	"easy-note/user/kitex_gen/user/user"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/kitex/client"
	consul "github.com/kitex-contrib/registry-consul"
	"log"
)

var h *server.Hertz
var conf *config.Config

func Init() {
	conf = config.GetConfig()
	serverConf := conf.Server.Gateway
	h = server.Default(
		server.WithHostPorts(serverConf.Addr),
		server.WithReadTimeout(serverConf.ReadTimeOut),
		server.WithWriteTimeout(serverConf.WriteTimeOut))
	routers.InitRouters(h)
	initClient()
}

func Start() {
	h.Spin()
}

func initClient() {
	r, err := consul.NewConsulResolver(conf.Consul.Addr)
	newUserClient, err := user.NewClient("easy-note.user", client.WithResolver(r))
	if err != nil {
		log.Fatalln(err)
	}
	newNoteClient, err := note.NewClient("note", client.WithHostPorts(conf.Server.Note.Addr))
	if err != nil {
		log.Fatalln(err)
	}
	handler.UserClient = newUserClient
	handler.NoteClient = newNoteClient
}
